function formatTimeObj(seconds) {
    const minutes = Math.floor(seconds / 60);
    const hours = Math.floor(minutes / 60);
    const remainMinutes = minutes % 60;

    return {
        hours,
        minutes: remainMinutes
    };
}

// 计算计算卡路里
export function calcStepData(myGoal, mySteps, weight = 60) {
    const stepLength = 0.7;
    const walkSpeed = 5;
    const distanceKm = (mySteps * stepLength) / 1000;
    const calories = weight * distanceKm;
    const timeHours = distanceKm / walkSpeed;
    const timeSeconds = timeHours * 3600;
    const goalDistanceKm = (myGoal * stepLength) / 1000;
    const goalCalories = weight * goalDistanceKm;
    const goalTimeMinutes = (goalDistanceKm / walkSpeed) * 60;
    return {
        steps: String(mySteps),
        goal: myGoal,
        distance: `${distanceKm.toFixed(2)}`,
        calories: `${calories.toFixed(1)}`,
        time: formatTimeObj(timeSeconds),
        goalDistance: `${goalDistanceKm.toFixed(2)}`,
        goalCalories: `${goalCalories.toFixed(0)}`,
        goalTime: formatTimeObj(goalTimeMinutes * 60),
    };
}

// 解析对应多疗程参数数据
export function parseTherapyPacketsSeparately(packetList: number[][]) {
    if (!Array.isArray(packetList) || packetList.length === 0) {
        throw new Error("packetList不能为空");
    }

    // 解析 4Byte 疗程时间（总天数或截止日期）
    function parseTherapyTime(bytes: number[]) {
        if (bytes.length !== 4) return { totalDays: null, endTime: null };

        // 先按截止日期解析（年低字节在前）
        const year = bytes[0] | (bytes[1] << 8);
        const month = bytes[2];
        const day = bytes[3];

        // 判断是否是合理的截止日期
        if (year >= 2000 && year <= 2100 && month >= 1 && month <= 12 && day >= 1 && day <= 31) {
            return { totalDays: null, endTime: `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}` };
        }

        // 如果不合理，则按总天数解析（低字节在前）
        const totalDays = bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24);
        return { totalDays, endTime: null };
    }

    // 解析单条小包
    function parsePacket(data: number[]) {
        const totalPackets = data[0];
        const packetIndex = data[1];
        const course_type_sn = data[2];
        const paramCount = data[3];
        const course_cycle_work_days = data[4];
        const course_cycle_rest_days = data[5];

        const { totalDays, endTime } = parseTherapyTime(data.slice(6, 10));

        const laserParams: number[][] = [];
        for (let i = 10; i < data.length; i += 4) {
            if (i + 4 <= data.length) laserParams.push(data.slice(i, i + 4));
        }

        return {
            header: { totalPackets, packetIndex, course_type_sn, paramCount, course_cycle_work_days, course_cycle_rest_days, totalDays, endTime },
            laserParams
        };
    }

    // 逐条解析并排序
    return packetList
        .map(parsePacket)
        .sort((a, b) => a.header.packetIndex - b.header.packetIndex);
}